//
//  CSSStatusListViewModel.swift
//  weibo28
//
//  Created by chushushan on 16/5/14.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//tableview对应的viewmodel
class CSSStatusListViewModel: NSObject {

    var  statusList: [CSSStatusViewModel]?
    //获取微博数据
    //isPullUp 判断是否是上拉
    func requestStatus(isPullUp: Bool, complete: (isSuccess: Bool, message: String) -> ()) {
        
        //上拉加载使用的默认maxid
        var maxId: Int64 = 0
        //下拉刷新默认sinceId
        var sinceId: Int64 = 0
        
        
        //是上拉
        if isPullUp {
            //代表上拉加载更多，需要获取数组里面最后一条微博的id
            maxId = statusList?.last?.status?.id ?? 0
        
            if maxId > 0 {
            //  去除重复的微博信息
                maxId -= 1
            }
        
        } else {
        
            sinceId = statusList?.first?.status?.id ?? 0
        
        }
        
        
        CSSNetWorkingTools.sharedTools.requsetStatus(CSSUserAccountViewModel.shareUserAccount.accessToken!, maxId: maxId, sinceId: sinceId) { (response, error) -> () in
            var message: String = "没有加载到微博数据"
            
            if error != nil {
                print("网络请求异常")
                complete(isSuccess: false, message: message)
                return
            }
            
            guard let dic = response as? [String: AnyObject] else {
                
                print("不是一个正常的json格式")
                complete(isSuccess: false, message: message)
                return
            }
            
            guard let statusesArray = dic["statuses"] as? [[String: AnyObject]] else {
                complete(isSuccess: false, message: message)
                print("不是一个正常的json格式")
                return
            }
            
            //遍历数组
            var tempArray = [CSSStatusViewModel]()
            for value in statusesArray {
                let status = CSSStatus(dic: value)
                let statusViewModel = CSSStatusViewModel(status: status)
                tempArray.append(statusViewModel)
                
            }

            
            if self.statusList == nil {
            
            self.statusList = [CSSStatusViewModel]()
            }
            
            //如果是上拉刷新
            if isPullUp {
            //上拉加载的时候，把数据加在当前数组的后面
                self.statusList = self.statusList! + tempArray
            } else {
            //不是上拉加载的时候，把数据加在当前数组的前面
                self.statusList = tempArray + self.statusList!
            }
            
            
            //刷新数据
//            self.statusList = tempArray
            
            let count = tempArray.count
            if count > 0 {
                message = "加载了\(count)条微博数据"
            }
            complete(isSuccess: true, message: message)
            
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
